package com.gb.demand.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gb.demand.common.api.ResultMap;
import com.gb.demand.common.entity.Apilog;
import com.gb.demand.common.entity.Usergoodsclass;
import com.gb.demand.common.mapper.UsergoodsclassMapper;
import com.gb.demand.service.IApilogService;
import com.gb.demand.service.IStoreService;
import com.gb.demand.service.IUsergoodsclassService;
import com.gb.demand.service.ex.MyEx.UserGoodsClassException;
import com.gb.demand.service.ex.ServiceException;
import com.gb.demand.util.JsonUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * 用户业务层模块<p>
 *
 * @author wengjiangle
 * @since 2020/7/13
 */
@Slf4j
@Service
public class UsergoodsclassServiceImpl extends ServiceImpl<UsergoodsclassMapper, Usergoodsclass> implements IUsergoodsclassService {

    @Autowired
    private IApilogService apilogService;

    @Autowired
    private IStoreService storeService;

    @Resource
    private UsergoodsclassMapper usergoodsclassMapper;

    /**
     * 获取品类(目录)接口
     *
     * @param data
     * @return
     */
    @Override
    public Map getProductCategory(String data) {
        Map appinfoMap = JsonUtils.str2obj(data, Map.class);//寄送字符串转成map
        String accessToken = String.valueOf(appinfoMap.get("accessToken"));
        String appKey = String.valueOf(appinfoMap.get("appKey"));
        // 判断token是否过期
        boolean isExpired = true;
        try {
            isExpired = storeService.checkAccessToken(appKey, accessToken);
        } catch (ServiceException e) {
            // 日志
            addApiLog(appKey, data, JsonUtils.obj2string(ResultMap.generateResultMapwithKey("result", "", e.getMessage(), false)), "新点-获取品类(目录)接口");
            return ResultMap.generateResultMapwithKey("result", "", e.getMessage(), false);
        } catch (Exception e) {
            // 日志
            addApiLog(appKey, data, JsonUtils.obj2string(ResultMap.generateResultMapwithKey("result", "", e.getMessage(), false)), "新点-获取品类(目录)接口");
            return ResultMap.generateResultMapwithKey("result", "", e.getMessage(), false);
        }
        // 如果没有过期，获取本店铺的用户自定义分类
        if (isExpired) {
            List<Usergoodsclass> userGoodsClassList = usergoodsclassMapper.findAllUGCbyAppKey(appKey);//获取所有的自定义分类
            try {
                List<Map> ugcResultList = this.generateUGCResult(userGoodsClassList);
                // 日志
                addApiLog(appKey, data, JsonUtils.obj2string(ResultMap.generateResultMapwithKey("result", ugcResultList, "获取用户自定义分类成功", true)), "新点-获取品类(目录)接口");
                return ResultMap.generateResultMapwithKey("result", ugcResultList, "获取用户自定义分类成功", true);
            } catch (ServiceException e) {
                // 日志
                addApiLog(appKey, data, JsonUtils.obj2string(ResultMap.generateResultMapwithKey("result", "", e.getMessage(), false)), "新点-获取品类(目录)接口");
                return ResultMap.generateResultMapwithKey("result", "", e.getMessage(), false);
            }
        } else {
            // 日志
            addApiLog(appKey, data, JsonUtils.obj2string(ResultMap.generateResultMapwithKey("result", "", "Token过期失效", false)), "新点-获取品类(目录)接口");
            return ResultMap.generateResultMapwithKey("result", "", "Token过期失效", false);
        }
    }

    @Override
    public BigDecimal findUGCDiscountByUGCID(String categoryId, String appKey) {
        String discount=usergoodsclassMapper.findUGCDiscountByUGCID(categoryId,appKey);
        BigDecimal dis=new BigDecimal(discount);
        dis=dis.setScale(2,BigDecimal.ROUND_HALF_UP);
        return dis;
    }

    /**
     * 日志记录
     *
     * @param caller      调用者
     * @param inputvalue  输入参数
     * @param outputvalue 输出参数
     * @param remark      备注
     */
    public void addApiLog(String caller, String inputvalue, String outputvalue, String remark) {
        // 记录调用日志
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Apilog apilog = new Apilog(new Date(), false, "", request.getRequestURL().toString(), caller, inputvalue, outputvalue, remark);
        apilogService.save(apilog);
    }

    /**
     * 按店铺 appKey 找出该店铺中的所有自定义分类
     *
     * @return
     */
    public List<Map> generateUGCResult(List<Usergoodsclass> ugcList) {
        if (ugcList.size() > 0) {
            List ugcResultList = new ArrayList();
            for (Usergoodsclass ugc : ugcList) {
                Map map = new HashMap();
                map.put("name", ugc.getClassName());
                map.put("categoryId", ugc.getEpointid());
                ugcResultList.add(map);
            }
            return ugcResultList;
        } else {
            throw new UserGoodsClassException("指定店铺中没有自定义分类");
        }
    }
}
